package com.xiaochun.hxhj;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bean.VideoListBean;
import com.myview.CustomProgressDialog;
import com.myview.MyVideoView;
import com.util.DensityUtil;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;

public class VideoPlayDetailActivity extends Activity {

    @BindView(R.id.videoview)
    MyVideoView videoview;
    @BindView(R.id.seek_progress)
    SeekBar seek_progress;
    @BindView(R.id.tv_time_progress)
    TextView tv_time_progress;
    @BindView(R.id.tv_time_all)
    TextView tv_time_all;
    @BindView(R.id.img_stop)
    ImageView img_stop;
    @BindView(R.id.img_screen)
    ImageView img_screen;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.ll_seekbar)
    LinearLayout ll_seekbar;
    @BindView(R.id.ll_title)
    LinearLayout ll_title;

    private List<VideoListBean.DataBeanX.DataBean> booklist = new ArrayList<>();
    private List<VideoListBean.DataBeanX.DataBean> booklisttemp = new ArrayList<>();
    private CustomProgressDialog customProgressDialog;
    private String url;
    private String id;
    boolean isplayover = false;
    private Integer currentprogress = 0;
    private long lasttime = 0;
    private Handler handlerdelay;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videoplaydetail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        context = this;
        customProgressDialog = new CustomProgressDialog(this, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        initView();
        initListener();

//        ActionBar actionBar = getSupportActionBar();
//        actionBar.hide();
//        customProgressDialog.show();
    }


    protected void initListener() {
        img_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int progress = seek_progress.getProgress();
                String trim = tv_time_progress.getText().toString().trim();
                EventBus.getDefault().post(new InfoEventMessage("视频进度",progress+"="+trim));
                finish();
            }
        });
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int progress = seek_progress.getProgress();
                String trim = tv_time_progress.getText().toString().trim();
                EventBus.getDefault().post(new InfoEventMessage("视频进度",progress+"="+trim));
                finish();
            }
        });

        img_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DensityUtil.isFastDoubleClick()){
                    return;
                }

                if (isplayover){
                    //说明整段视频播放完毕，重新点击播放按钮，就从头重新播放该段视频
                    //视频的总时长，并关联SeekBar的总长度
                    int duration = videoview.getDuration();
                    Log.e("视频总时长按钮", duration + "  转换成秒  " + duration / 1000);
                    SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                    formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                    String hms = formatter.format(duration);
                    tv_time_all.setText(hms);

                    //设置SeekBar进度的总长
                    seek_progress.setMax(duration);
                    seek_progress.setProgress(0);
                    videoview.seekTo(0);
                    handler.sendEmptyMessage(0);
                    isplayover = false;
                }
                startAndPause();
            }
        });

    }
    //播放和暂停视频
    private void startAndPause() {
        if (videoview.isPlaying()) {
            //视频在播放-设置暂停
            videoview.pause();
            //按钮状态设置播放
            img_stop.setImageResource(R.mipmap.icon_playstop);
        } else {
            //视频播放
            videoview.start();
            //按钮状态设置暂停
            img_stop.setImageResource(R.mipmap.icon_play);
        }
    }


    protected void initView() {

        url = getIntent().getStringExtra("url");
        id = getIntent().getStringExtra("id");
        String progress = getIntent().getStringExtra("progress");
        currentprogress = Integer.parseInt(progress);
        String inittime = getIntent().getStringExtra("inittime");
        String url = getIntent().getStringExtra("url");
        handlerdelay = new Handler();
        tv_time_progress.setText(inittime);

        videoview.setVideoURI(Uri.parse(url));
        videoview.start();

        seek_progress.setOnSeekBarChangeListener(mSeekBarListener);
        videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                Log.e("播放完成", "时间暂停");
                handler.removeMessages(0);
                String trim = tv_time_all.getText().toString().trim();
                tv_time_progress.setText(trim);
                videoview.pause();
                //按钮状态设置播放
                img_stop.setImageResource(R.mipmap.icon_playstop);
                isplayover = true;


            }
        });
        //设置发生错误监听，如果不设置videoview会向用户提示发生错误
        videoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        //设置在视频文件在加载完毕以后的回调函数   168160   167844
        videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
                            videoview.setBackgroundColor(Color.TRANSPARENT);
                        return true;
                    }
                });
                //视频的总时长，并关联SeekBar的总长度
                int duration = videoview.getDuration();
                Log.e("视频总时长准备", duration + "  转换成秒  " + duration / 1000);
                SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                String hms = formatter.format(duration);
                tv_time_all.setText(hms);

                //设置SeekBar进度的总长
                seek_progress.setMax(duration);
                seek_progress.setProgress(currentprogress);
                videoview.seekTo(currentprogress);

                handlerdelay.removeCallbacksAndMessages(null);
                handlerdelay.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ll_title.setVisibility(View.GONE);
                        ll_seekbar.setVisibility(View.GONE);
                    }
                },3000);
                handler.sendEmptyMessage(0);

            }
        });
        //设置videoView的点击监听
        videoview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        ll_title.setVisibility(View.VISIBLE);
                        ll_seekbar.setVisibility(View.VISIBLE);

                        handlerdelay.removeCallbacksAndMessages(null);
                        handlerdelay.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ll_title.setVisibility(View.GONE);
                                ll_seekbar.setVisibility(View.GONE);
                            }
                        },3000);


                        long l = System.currentTimeMillis();
                        if (lasttime == 0){
                            lasttime = l;
                        }else{
                            long timecha = l - lasttime;
                            if (timecha > 500){
                                lasttime = l;
                            }else{
                                lasttime = l;
                                startAndPause();
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:


                        break;
                }

                return false;
            }
        });

        videoview.setPlayListener(new MyVideoView.PlayListener() {
            @Override
            public void onPause() {
                int currentPosition = videoview.getCurrentPosition();
                Log.e("视频播放暂停位置", currentPosition + "    暂停毫秒");

                seek_progress.setProgress(currentPosition);
            }

            @Override
            public void onStart() {
                int currentPosition = videoview.getCurrentPosition();
                int as = currentPosition + 1;
                Log.e("视频播放开始位置", as + "    开始毫秒");
//                videoView.seekTo(as);
                videoview.seekTo(currentPosition);
            }
        });



    }
    /**
     * 进度拖动条监听器
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
        // 通知进度已经被修改
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                videoview.seekTo(progress);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = seekBar.getProgress();
                handler.removeMessages(0);
//                handler.sendMessageAtTime(msg, 0);// 1秒之后开始发送更新进度的消息
                handler.sendEmptyMessage(0);
            }
        }

        // 通知用户已经开始一个触摸拖动手势
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        // 通知用户触摸手势已经结束
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };




    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);



                    break;
                case 3:


                    break;
                case 4:

                    break;
                case 5:

                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
            switch (msg.what) {
                case 0:
                    //1.得到当前的视频播放进程
                    int currentPosition = videoview.getCurrentPosition();//0
//                    Log.e("播发进度",currentPosition+"    播放进度");
                    //2.SeekBar.setProgress(当前进度);
                    seek_progress.setProgress(currentPosition);
                    //3.更新文本播放进度
                    SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//这里想要只保留分秒可以写成"mm:ss"
                    formatter.setTimeZone(TimeZone.getTimeZone("00:00"));
                    String hms = formatter.format(currentPosition);
                    tv_time_progress.setText(hms);

                    //4.每秒更新一次
                    handler.removeMessages(0);
                    handler.sendEmptyMessageDelayed(0, 0);
                    break;
                case 1:
                    break;


            }
        }
    };




    @Override
    protected void onResume() {
        super.onResume();
        videoview.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*int progress = seek_progress.getProgress();
        String trim = tv_time_progress.getText().toString().trim();
        EventBus.getDefault().post(new InfoEventMessage("视频进度",progress+"="+trim));*/
        EventBus.getDefault().unregister(this);
        handler.removeCallbacksAndMessages(null);
    }

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,VideoPlayDetailActivity.this,tv_time_all);
//            popbyexit(type);
        }
    }
}
